package com.demo.reader_;

import org.apache.log4j.Logger;
import org.junit.Test;

import java.io.FileReader;
import java.io.IOException;

/**
 * @author gy
 * @date 2022/4/4
 */
public class FileReader01 {

    private static final Logger logger = Logger.getLogger(FileReader01.class);

    public static void main(String[] args) {
    }
    /**
     * 单个字符文件读取
     */
    @Test
    public void m1() {
        String filePath = "f:\\20220403\\fileReader.txt";

        FileReader fileReader = null;
        int data = 0;
        try {
            logger.info("创建 字符 输入流对象");
            fileReader = new FileReader(filePath);
            // 循环读取，使用 read 逐个读取
            while ((data = fileReader.read()) != -1) {
                System.out.print(((char) data));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    public void m2() {
        String filePath = "f:\\20220403\\fileReader.txt";

        FileReader fileReader = null;
        int readLength = 0;
        char[] buf = new char[30];
        try {
            logger.info("创建 字符 输入流对象");
            fileReader = new FileReader(filePath);
            // 循环读取，使用 read(buf) 返回到的是循环读取的字符数
            while ((readLength = fileReader.read(buf)) != -1) {
                System.out.println("=============");
                System.out.print(new String(buf,0,readLength));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
